//
//  YZMSpreadUserView.m
//  YZMicroStock
//
//  Created by apple on 17/1/4.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "YZMSpreadUserView.h"
#import "YZMSpreadUserCell.h"
#import "YZMSpreadNoUserCell.h"
#import "YZMSpreadUserHeaderView.h"
#import "YZClient.h"
#import "YZMUserSpreadModel.h"
#import "YZMUserSpreadPacket.h"
#import <MJRefresh.h>
#import "YZMPageService.h"

static NSString *const YZMSpreadUserCellID=@"YZMSpreadUserCell";
static NSString *const YZMSpreadNoUserCellID=@"YZMSpreadNoUserCell";
static NSString *const YZMSpreadHeaderViewID=@"YZMSpreadUserHeaderView";

@interface YZMSpreadUserView ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *datasource;
@property(nonatomic, strong) MJRefreshAutoNormalFooter *refreshFooter;
@property(nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property(nonatomic, strong) YZMPageService *pageService;



@end

@implementation YZMSpreadUserView

-(instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        [self createObject];
    }
    return self;
}

-(NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource=[NSMutableArray array];
    }
    return _datasource;
}


-(void)createObject{
    self.backgroundColor=[YZMAppStyle appBackgroundColor];
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)style:UITableViewStyleGrouped];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self addSubview:self.tableView];
    
    _pageService = [YZMPageService new];
    
    [self fetchSuggestionListFirstPage];
    
    self.refreshHeader=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self fetchSuggestionListFirstPage];
    }];
    
    self.refreshHeader.lastUpdatedTimeLabel.textColor=[YZMAppStyle colorForLightGrayText];
    self.refreshHeader.lastUpdatedTimeLabel.font=[YZMAppStyle smallSizeFont];
    
    self.refreshHeader.stateLabel.textColor=[YZMAppStyle colorForLightGrayText];
    self.refreshHeader.stateLabel.font=[YZMAppStyle smallSizeFont];
    
    self.tableView.mj_header=self.refreshHeader;
    
    self.refreshFooter=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self fetchSuggestionListNextPage];
    }];
    
    self.refreshFooter.stateLabel.textColor=[YZMAppStyle colorForLightGrayText];
    self.refreshFooter.stateLabel.font=[YZMAppStyle smallSizeFont];
    self.tableView.mj_footer=self.refreshFooter;
    
    self.tableView.backgroundColor=[YZMAppStyle appBackgroundColor];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self);
    }];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[YZMSpreadUserCell class] forCellReuseIdentifier:YZMSpreadUserCellID];
    [self.tableView registerClass:[YZMSpreadNoUserCell class] forCellReuseIdentifier:YZMSpreadNoUserCellID];
    [self.tableView registerClass:[YZMSpreadUserHeaderView class] forHeaderFooterViewReuseIdentifier:YZMSpreadHeaderViewID];
}

-(void)reloadData{
    
    [self fetchSuggestionListFirstPage];
}

- (void)fetchSuggestionListFirstPage{
    
    [_pageService preChangeWithPage:_pageService.minPage andTimeEnd:YES];
    [self getListData];
}


- (void)fetchSuggestionListNextPage{
    
    [_pageService preChangeWithPage:_pageService.nextPage andTimeEnd:YES];
    [self getListData];
}

- (void)endRefresh{
    
    if (_refreshHeader.isRefreshing) {
        
        [_refreshHeader endRefreshing];
    }
    
    if (_refreshFooter.isRefreshing) {
        
        [_refreshFooter endRefreshing];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.datasource.count>0) {
        return self.datasource.count;
    }
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.datasource.count>0) {
        YZMSpreadUserCell *Cell=[tableView dequeueReusableCellWithIdentifier:YZMSpreadUserCellID forIndexPath:indexPath];
        
        YZMIndexCount indexCount;
        indexCount.index = indexPath.row;
        indexCount.count = _datasource.count;
        Cell.indexCount = indexCount;
        Cell.leftMargin = 10;
        Cell.rightMargin = 10;
        
        Cell.bottomLineView.hidden=NO;
        
        Cell.selectionStyle=UITableViewCellSelectionStyleNone;
        YZMUserSpreadModel *model=self.datasource[indexPath.row];
        Cell.model=model;
        
        return Cell;
    }
    
    YZMSpreadNoUserCell *Cell=[tableView dequeueReusableCellWithIdentifier:YZMSpreadNoUserCellID forIndexPath:indexPath];
    
    Cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    return Cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.datasource.count>0) {
        return 44;
    }
    return self.frame.size.height;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YZMSpreadUserHeaderView *headerView=[tableView dequeueReusableHeaderFooterViewWithIdentifier:YZMSpreadHeaderViewID];
    if (self.datasource.count>0) {
        headerView.topLine.hidden=NO;
    }else{
        headerView.topLine.hidden=YES;
    }
    return headerView;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

-(void)getListData{
    /*无网处理*/
    if (kNetworkNotReachability) {
        if ( self.datasource.count == 0) {
            self.tableView.mj_header = nil;
            self.tableView.mj_footer=nil;
        }else{
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    
    [YZClient fetchSpreadUserListWithPage:self.pageService.tempPage andPageSize:self.pageService.pageSize success:^(NSURLResponse *response, id responseObject) {
        [self endRefresh];
        
        self.tableView.mj_header = _refreshHeader;
        self.tableView.mj_footer = _refreshFooter;
        
        YZGeneralResultModel *topModel = responseObject;
        
        if (topModel.success) {
            
            YZMUserSpreadPacket *model=topModel.data;
            NSArray *array = model.dataList;
            NSInteger pageIndex=model.pageIndex;
            if (pageIndex==_pageService.minPage) {
                [self.datasource removeAllObjects];
                [self.datasource addObjectsFromArray:array];
            }else{
                [self.datasource addObjectsFromArray:array];
            }
            
            if (model.pageIndex>=model.totalPage) {
                if (self.datasource.count==0) {
                    self.tableView.mj_footer=nil;
                }else{
                    _refreshFooter.state=MJRefreshStateNoMoreData;
                    [self.refreshFooter setTitle:[NSString stringWithFormat:@"(共%@人，交易%@人)",@(model.totalUserCount),@(model.tradeCount)] forState:MJRefreshStateNoMoreData];
                }
            }else{
                _refreshFooter.state=MJRefreshStateIdle;
                [self.refreshFooter setTitle:[NSString stringWithFormat:@"查看更多（共%@人，交易%@人）",@(model.totalUserCount),@(model.tradeCount)] forState:MJRefreshStateIdle];
            }
            
            [self.tableView reloadData];
            [_pageService effectChange];
        }else{
            if (self.datasource.count==0) {
                self.tableView.mj_footer=nil;
                self.tableView.mj_header=nil;
            }else{
                [topModel showMessage];
            }
        }

    } failure:^(NSError *error) {
        [self endRefresh];
        //网络异常处理
        if (self.datasource.count == 0) {
            self.tableView.mj_header = nil;
            self.tableView.mj_footer = nil;
        }else{
            [error yz_showMessage];
        }
    }];
}

@end
